
const Koa = require('koa')
const cors = require('koa2-cors');
const consola = require('consola')
const { Nuxt, Builder } = require('nuxt')

// import mongoose from 'mongoose'
// import dbConfig from './dbs/config'

const bodyParser = require('koa-bodyparser')
const session = require('koa-generic-session')
const Redis = require('koa-redis')
const json = require('koa-json')
const passport = require('./api/utils/passport')
// api
const users = require('./api/users')
const website = require('./api/website')
// const geo = require('./api/geo')
// const search = require('./api/search')
// const categroy = require('./api/categroy')
// const cart = require('./api/cart')
const mongoose = require('mongoose')
const dbConfig = require('./dbs/config')

// ------------------------------
mongoose.connect(dbConfig.dbs, {
  useNewUrlParser: true
})

const app = new Koa()
app.use(cors())
const host = process.env.HOST || '127.0.0.1'
const port = process.env.PORT || 3000

// Import and Set Nuxt.js options
let config = require('../nuxt.config.js')
config.dev = !(app.env === 'production')


app.keys = ['mt', 'keyskeys']
app.proxy = true
app.use(session({key: 'mt', prefix: 'mt:uid', store: new Redis()}))
app.use(bodyParser({
  extendTypes:['json','form','text']
}))
app.use(json())

mongoose.connect(dbConfig.dbs,{
  useNewUrlParser:true
})
app.use(passport.initialize())
app.use(passport.session())


// mongo
// const mongoose = require('mongoose')
// const dbConfig = require('./dbs/config')

// mongoose.connect(dbConfig.dbs, {
//   useNewUrlParser: true
// })
// mongoose.connect('mongodb://121.41.55.136:27017/blog')

async function start() {
  // Instantiate nuxt.js
  const nuxt = new Nuxt(config)

  // Build in development
  if (config.dev) {
    const builder = new Builder(nuxt)
    await builder.build()
  }

  // router
  // app.use(users.routes()).use(route.get('/demo', demo));
  app.use(users.routes()).use(users.allowedMethods())
  app.use(website.routes()).use(website.allowedMethods())
  // app.use(geo.routes()).use(geo.allowedMethods())
  // app.use(search.routes()).use(search.allowedMethods())
  // app.use(categroy.routes()).use(categroy.allowedMethods())
  // app.use(cart.routes()).use(cart.allowedMethods())

  app.use(ctx => {
    ctx.status = 200 // koa defaults to 404 when it sees that status is unset

    return new Promise((resolve, reject) => {
      ctx.res.on('close', resolve)
      ctx.res.on('finish', resolve)
      nuxt.render(ctx.req, ctx.res, promise => {
        // nuxt.render passes a rejected promise into callback on error.
        promise.then(resolve).catch(reject)
      })
    })
  })

  app.listen(port, host)
  consola.ready({
    message: `Server listening on http://${host}:${port}`,
    badge: true
  })
}

start()
